<template>
  <div class="app-container">
    <div class="search-bar">
      <el-form ref="queryFormRef" :model="queryParams" :inline="true">
        <el-form-item prop="name" :label="$t('customer.region.name')">
          <el-input
            v-model="queryParams.customerName"
            :placeholder="$t('customer.region.name')"
            clearable
            @keyup.enter="handleQuery"
          />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" icon="search" @click="handleQuery">
            {{ $t("common.search") }}
          </el-button>
          <el-button icon="refresh" @click="handleResetQuery">{{ $t("common.reset") }}</el-button>
        </el-form-item>
      </el-form>
    </div>

    <el-card shadow="never">
      <div class="mb-10px">
        <el-button
          v-hasPerm="'region:add'"
          type="success"
          icon="plus"
          @click="handleOpenDialog(0, 0)"
        >
          {{ $t("common.add") }}
        </el-button>

        <div class="text-right">
          <el-switch
            v-model="switchForm"
            size="large"
            class="ml-2"
            :active-text="$t('customer.region.switchFormActiveText')"
            inactive-text=""
            @change="handleSwitchForm"
          />
        </div>
      </div>
      <el-table ref="dataTableRef" v-loading="loading" stripe :data="list" highlight-current-row>
        <el-table-column :label="$t('customer.region.name')" prop="customerName" />
        <el-table-column fixed="right" :label="$t('common.action')" width="220">
          <template #default="scope">
            <el-button
              v-hasPerm="'region:edit'"
              type="primary"
              size="small"
              link
              icon="edit"
              @click="handleOpenDialog(scope.row.customerId, 0)"
            >
              {{ $t("common.edit") }}
            </el-button>

            <el-button
              v-hasPerm="'region:delete'"
              type="danger"
              size="small"
              link
              icon="delete"
              @click="handleDelete(scope.row.customerId)"
            >
              {{ $t("common.delete") }}
            </el-button>
          </template>
        </el-table-column>
      </el-table>

      <pagination
        v-if="total > 0"
        v-model:total="total"
        v-model:page="queryParams.pageNum"
        v-model:limit="queryParams.pageSize"
        @pagination="handleQuery"
      />
    </el-card>
    <el-dialog
      v-model="dialog.visible"
      :title="dialog.title"
      :width="dialogWidth"
      @close="handleCloseDialog"
    >
      <el-form ref="iFormRef" :model="formData" :rules="rules">
        <el-form-item :label="$t('customer.region.name')" prop="customerName">
          <el-input
            v-model="formData.customerName"
            :placeholder="$t('common.plsInput') + $t('customer.region.name')"
          />
        </el-form-item>
      </el-form>

      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="handleSubmity">{{ $t("common.confirm") }}</el-button>
          <el-button v-if="showApply" type="success" @click="handleSubmitApply">
            {{ $t("common.keepAdd") }}
          </el-button>
          <el-button @click="handleCloseDialog">{{ $t("common.cancel") }}</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { ref } from "vue";
import { useI18n } from "vue-i18n";
const { t } = useI18n();
defineOptions({
  name: "Region",
  inheritAttrs: false,
});

import RegionApi, { IForm, IPageQuery, IPageVO } from "@/api/system/region";
import CustomerAPI from "@/api/customer";
const screenWidth = window.innerWidth;
const dialogWidth = screenWidth < 768 ? "90%" : "500px";
const queryFormRef = ref(ElForm);
const iFormRef = ref(ElForm);
const showApply = ref(false);

const loading = ref(false);
const total = ref(0);

const queryParams = reactive<IPageQuery>({
  pageNum: 1,
  pageSize: 10,
  customerName: "",
});

const list = ref<IPageVO[]>();

const dialog = reactive({
  title: "",
  visible: false,
});

const switchForm = ref(false);

const formData = reactive<IForm>({
  customerId: undefined,
  customerName: "",
});

const rules = reactive({
  name: [
    { required: true, message: t("common.plsInput") + t("customer.region.name"), trigger: "blur" },
  ],
});

function handleQuery() {
  loading.value = true;
  RegionApi.getList(queryParams)
    .then((data) => {
      list.value = data.list;
      total.value = data.total;
    })
    .finally(() => {
      loading.value = false;
    });
}

function handleResetQuery() {
  queryFormRef.value.resetFields();
  queryParams.pageNum = 1;
  handleQuery();
}

const keepAdd = ref(false);
function handleOpenDialog(id?: number, type?: number) {
  dialog.visible = true;
  if (type === 1) {
    keepAdd.value = true;
  }
  if (id) {
    showApply.value = false;
    dialog.title = t("common.edit");
    RegionApi.getFormData(id).then((data) => {
      Object.assign(formData, data);
    });
  } else {
    showApply.value = true;
    dialog.title = t("common.add");
  }
}

function handleSubmity() {
  keepAdd.value = false;
  handleSubmit();
}

function handleSubmitApply() {
  keepAdd.value = true;
  handleSubmit();
}

function handleSubmit() {
  iFormRef.value.validate((valid: any) => {
    if (valid) {
      loading.value = true;
      const id = formData.customerId;
      if (id) {
        RegionApi.update(formData)
          .then((res) => {
            if (res.data.code === 200) {
              ElMessage.success(res.data.message);
              handleCloseDialog();
              handleResetQuery();
            } else {
              ElMessage.error(res.data.message);
            }
          })
          .finally(() => (loading.value = false));
      } else {
        RegionApi.add(formData)
          .then((res) => {
            ElMessage.success(res.data.message);
            if (keepAdd.value) {
              handleResetForm();
            } else {
              handleCloseDialog();
            }
            handleResetQuery();
          })
          .finally(() => (loading.value = false));
      }
    }
  });
}

function handleResetForm() {
  iFormRef.value.resetFields();
  iFormRef.value.clearValidate();

  formData.customerId = undefined;
  formData.customerName = "";
}

function handleCloseDialog() {
  dialog.visible = false;
  keepAdd.value = false;
  iFormRef.value.resetFields();
  iFormRef.value.clearValidate();

  formData.customerId = undefined;
  formData.customerName = "";
}

function handleDelete(id: number) {
  ElMessageBox.confirm(t("common.confirmDelete"), t("common.warning"), {
    confirmButtonText: t("common.confirm"),
    cancelButtonText: t("common.cancel"),
    type: "warning",
  }).then(
    () => {
      loading.value = true;
      RegionApi.deleteByIds(id)
        .then((res) => {
          if (res.data.code === 200) {
            ElMessage.success(res.data.message);
            handleResetQuery();
          } else {
            ElMessage.error(res.data.message);
          }
        })
        .finally(() => (loading.value = false));
    },
    () => {
      ElMessage.info(t("common.cancelDelete"));
    }
  );
}

function handleSwitchForm() {
  let xstatus = 0;
  if (switchForm.value == true) {
    xstatus = 1;
  } else {
    xstatus = 0;
  }
  CustomerAPI.setRegionSwitchUq(xstatus).then((res) => {
    if (res.data.code === 200) {
      if (res.data.message.includes("forbid_change")) {
        switchForm.value = !switchForm.value;
        ElMessage.error(t("customer.region.cannotChnage"));
        return;
      }
      ElMessage.success(t("customer.region.regionUqSuc"));
    } else {
      ElMessage.error(t("customer.region.regionUqFail"));
    }
  });
}

function handleQuerySwitchForm() {
  CustomerAPI.getCurrentLogedUsersCustomer().then((res) => {
    if (res.mainRegionuq == 1) {
      switchForm.value = true;
    } else {
      switchForm.value = false;
    }
  });
}

onMounted(() => {
  handleQuerySwitchForm();
  handleQuery();
});
</script>
